import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.imageio.ImageIO;

public class AutoConverSprite {

	/**
	 * @param args
	 */
	static String pathDirectory = null;
	static String[] allSPriteFiles = null;
	static AutoConverSprite autoMapFont;
	static String NOTEString = "----------------------------------------------------\n"
			+ "CHUONG TRINH CONVERT SPRITE DATA TU FILE MAU \n"
			+ "HIEN TAI CHI SU LI CHO FILE ANH PNG TU CHUONG TRINH \n"
			+ "TAT CA CAC FILE TRONG THU MUC SE DUOC SU LI \n"
			+ "----------------------------------------------------";

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// Image img = new
		// get current dir
		System.out.println(NOTEString);
		autoMapFont = new AutoConverSprite();
		pathDirectory = getCurentDirectory();
		allSPriteFiles = getAllListFile(pathDirectory, ".sprite");
		for (int i = 0; i < allSPriteFiles.length; i++)
			convert(pathDirectory + "\\" + allSPriteFiles[i]);

	}

	public static String getCurentDirectory() {
		String str = null;
		try {
			str = new java.io.File(".").getCanonicalPath();
			System.out.println("Current directory : " + str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}

	public static String[] getAllListFile(String path, String fileExtendtion) {
		File folder = new File(path);
		String fille[] = null;
		File[] listOfFiles = folder.listFiles();

		int count = 0;
		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				if (listOfFiles[i].getName().indexOf(fileExtendtion) > 0)
					count++;

			}
		}
		fille = new String[count];
		count = 0;

		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				if (listOfFiles[i].getName().indexOf(fileExtendtion) > 0) {
					fille[count] = listOfFiles[i].getName();
					count++;
				}
			}
		}
		return fille;
	}

	public static int step = 0;

	public static void convert(String filename) {

		try {
			// use buffering, reading one line at a time
			// FileReader always assumes default encoding is OK!
			BufferedReader input = new BufferedReader(new FileReader(filename));
			
			String outputFile = filename.substring(0, filename.indexOf("."))
					+ ".spr";
			FileWriter fstream = new FileWriter(outputFile);
			BufferedWriter out = new BufferedWriter(fstream);
			try {
				String line = null; // not declared within while loop
				/*
				 * readLine is a bit quirky : it returns the content of a line
				 * MINUS the newline. it returns null only for the END of the
				 * stream. it returns an empty String if two newlines appear in
				 * a row.
				 */
				int numOfModules = 0;
				int numOfFrames = 0;
				int numOfAnims = 0;
				int numModuleinFrame = 0;
				int numFrameinAnime = 0;
				String imageName = "";
				int index1 = 0;
				int index2 = 0;
				int countM_F_A_Loading = 0;
				int[][] arrayValueOfModule = null;
				int[][] arrayValueOffFrame = null;
				String strTemp = "";
				while ((line = input.readLine()) != null) {
					// xu li o day
					// xu li module truoc
					// Modules:
					line = line.trim();
					line = line.replace("	", " ");// mot cai la tab mot cai la
					// space
					switch (step) {
					case 0:
						if (line.indexOf("// Modules:") >= 0) {
							strTemp = line.substring(12).trim();// 12 = chieu
							// dai cua
							// "// Modules:"
							numOfModules = Integer.valueOf(strTemp);
							System.out.println("So Module :" + numOfModules);
							arrayValueOfModule = new int[numOfModules][5];
							step++;
						}
						break;
					case 1:
						if (line.indexOf("// Frames:") >= 0) {
							strTemp = line.substring(10).trim();
							numOfFrames = Integer.valueOf(strTemp);
							System.out.println("So Frames :" + numOfFrames);
							arrayValueOffFrame = new int[numOfFrames][2];
							step++;
						}
						break;
					case 2:
						if (line.indexOf("// Anims:") >= 0) {
							strTemp = line.substring(9).trim();
							numOfAnims = Integer.valueOf(strTemp);
							System.out.println("So Frames :" + numOfAnims);
							step++;
						}
						break;
					case 3:
						if (line.indexOf("IMAGE 0x0000") >= 0) {

							index1 = line.indexOf("\"");
							strTemp = line.substring(index1 + 1);
							index2 = strTemp.indexOf("\"");
							imageName = strTemp.substring(0, index2);
							System.out.println("Image:" + imageName);
							//ghi cac thong tin header
							out.write("IMAGE 1 " +imageName +"\n");//ten file
							out.write("NUM_OF_MODULE " +numOfModules +"\n");//ten file
							out.write("NUM_OF_FRAME " +numOfFrames +"\n");//ten file
							out.write("NUM_OF_ANIM " +numOfAnims +"\n");//ten file
							out.write("//---------------------------------------\n");//ten file

							step++;
						}
						break;
					case 4:
						// xuat ra file
						if (line.indexOf("MD") == 0) {
							line = line.replaceAll("MD_IMAGE ", "").trim();// md
						
							line = line.replaceAll("MD ", "").trim();
							line = line.replaceAll("0x", "").trim();
							StringTokenizer st = new StringTokenizer(line, " ");
							Vector v = new Vector();
							while (st.hasMoreTokens()) {
								v.addElement(st.nextToken());
							}
						//	int count = v.size();
							arrayValueOfModule[countM_F_A_Loading][0] = Integer
									.parseInt((String) v.elementAt(0), 16);
							arrayValueOfModule[countM_F_A_Loading][1] = new Integer(
									((String) v.elementAt(2))).intValue();
							arrayValueOfModule[countM_F_A_Loading][2] = new Integer(
									((String) v.elementAt(3))).intValue();
							arrayValueOfModule[countM_F_A_Loading][3] = new Integer(
									((String) v.elementAt(4))).intValue();
							arrayValueOfModule[countM_F_A_Loading][4] = new Integer(
									((String) v.elementAt(5))).intValue();
							countM_F_A_Loading++;
						}
						if (countM_F_A_Loading >= numOfModules) {
							//
							for(int i=0;i<numOfModules;i++){
								out.write("    MODULE "+i+" "+arrayValueOfModule[i][1] +" "+
										arrayValueOfModule[i][2]+ " " +arrayValueOfModule[i][3] +" "+arrayValueOfModule[i][4]+ "\n");
							}
							out.write("//---------------------------------------\n");//ten file
							countM_F_A_Loading = 0;
							step++;
						}

						break;
					case 5:
						if (line.indexOf("FRAME") == 0) {							
							if (countM_F_A_Loading > 0)
								out.write("\n    }\n");
							line = line.substring(
									line.indexOf("FModules =") + 10).trim();

							out.write("    FRAME INDEX= "
									+ String.valueOf(countM_F_A_Loading)
									+ " COUNT=" + line + " NAME=" + "\n    {\n");
							arrayValueOffFrame[countM_F_A_Loading][1] = Integer.parseInt(line);//tong so	
							System.out.println(line);
							
						} else if( line.indexOf("0x") == 0){
							line = line.replaceAll("0x", "").trim();
							arrayValueOffFrame[countM_F_A_Loading ][0] = Integer.parseInt(line,16);							
						}
						else if (line.indexOf("FM") == 0) {							
							 //FM	0x100D	0	0
							
							line = line.replaceAll("0x", "").trim();
							line = line.substring(3);
							StringTokenizer st = new StringTokenizer(line, " ");
							Vector v = new Vector();
							while (st.hasMoreTokens()) {
								v.addElement(st.nextToken());
							}
							int count = v.size();
							int idModule =0;
							int x;
							int y;
							idModule= Integer.parseInt((String) v.elementAt(0), 16);
							for(int i =0;i<arrayValueOfModule.length;i++){
								if(idModule ==arrayValueOfModule[i][0])
								{
									idModule = i;
									break;
								}
							}
							x = Integer.parseInt((String) v.elementAt(1));
							y = Integer.parseInt((String) v.elementAt(2));
							out.write("        FRAME_MODULE "
									+ idModule +" "
									+x + " " + y+"\n");
							arrayValueOffFrame[countM_F_A_Loading][1]--;
							if(arrayValueOffFrame[countM_F_A_Loading][1] <=0)
								countM_F_A_Loading++;
						}
					
						// arrayValueOfFrame
						if (countM_F_A_Loading >= numOfFrames ) {
							countM_F_A_Loading = 0;
							out.write("    }\n");
							out.write("//---------------------------------------\n");//ten file
							step++;
						}
						break;
					case 6:
							if (line.indexOf("ANIM") == 0) {
								
							if (countM_F_A_Loading > 0)
								out.write("\n    }\n");
							line = line.substring(
									line.indexOf("AFrames =") + 10).trim();
							countM_F_A_Loading++;
							out.write("    ANIM INDEX= "
									+ String.valueOf(countM_F_A_Loading)
									+ " COUNT=" + line + " NAME=" + "\n    {\n");
							
						} else if (line.indexOf("AF") == 0) {
							 //FM	0x100D	0	0
							line = line.replaceAll("0x", "").trim();
							line = line.substring(3);
							StringTokenizer st = new StringTokenizer(line, " ");
							Vector v = new Vector();
							while (st.hasMoreTokens()) {
								v.addElement(st.nextToken());
							}
							int count = v.size();
							int idModule =0;
							int x;
							int y;
							int time;
							idModule= Integer.parseInt((String) v.elementAt(0), 16);
							for(int i =0;i<arrayValueOffFrame.length;i++){
								if(idModule == arrayValueOffFrame[i][0])
								{
									idModule = i;
									break;
								}
							}
							
							time  = Integer.parseInt((String) v.elementAt(1));
							x = Integer.parseInt((String) v.elementAt(2));
							y = Integer.parseInt((String) v.elementAt(3));
							out.write("        ANIM_FRAME "
									+ idModule +" "
									+x + " " + y+" "+time+ "\n");					

						}						

						break;
					default:
						break;
					}


				}
			} finally {
				out.write("    }\n");//ket thuc dong ngoac				
				input.close();
				out.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		System.out.println("End");

	}
}
